require 'rubygems'
require 'progressbar'

module Statistic
  
  class FieldsCounter
    
    public
    
    def initialize( crawl_table, conditions = "status = 200" )
      @stat_table = crawl_table
      @conditions = conditions
      @records_analyzed_fail = 0
      reset_analisys
    end
    
    def update_statistic
      reset_analisys
      record_to_analyse = @stat_table.count_by_sql "SELECT count(*) FROM #{@stat_table.table_name} WHERE #{@conditions}"
      last_progress_value = 0
      progress_value = last_progress_value 
      pbar = ProgressBar.new("#{@stat_table.table_name}", 100)
      
      @stat_table.find_each(:conditions => @conditions) { |c|       
        begin
          #if analyse(c) then
          analyse(c)
          @records_analyzed += 1
          progress_value = sprintf("%d", @records_analyzed.to_f / record_to_analyse * 100.0).to_i
          if  progress_value != last_progress_value then
            last_progress_value = progress_value
            pbar.set progress_value
          end
          #          else
          #            @records_analyzed_fail << c
          #          end
        rescue Exception => e
          @errors << [c, "#{e.to_s}\n#{e.backtrace.join("\n")}"]
        end
      }
      
      puts pbar.finish
      @fields_stat
    end
    
    def reset_analisys
      @fields_stat = Hash.new 0
      @records_analyzed = 0
      @records_analyzed_fail = []
      @errors = []
    end
    
    def errors
      @errors
    end
    
    def fields_stat
      @fields_stat
    end
    
    def records_analyzed
      @records_analyzed
    end
    
    def records_analyzed_fail 
      @records_analyzed_fail
    end
    
    protected
    
    def analyse(c)
      
    end
    
  end
  
end